package nancal.mp.mvc.sys


import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import nancal.mp.db.mongo.entity.sys.*
import nancal.mp.db.mongo.mor
import nbcp.base.annotation.*
import nbcp.base.annotation.mvc.*
import nbcp.base.comm.ApiResult
import nbcp.base.comm.JsonResult
import nbcp.base.db.IdCodeName
import nbcp.base.extend.*
import nbcp.base.json.*
import nbcp.mvc.sys.*
import nbcp.myoql.db.mongo.deleteById
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.mongo.queryById
import nbcp.myoql.db.mongo.updateWithEntity

import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
import javax.servlet.http.HttpServletRequest

/**
 * Created by CodeGenerator at 2022-05-27 17:28:52
 */
@Api(description = "langResource", tags = arrayOf("LangResource"))
@RestController
@OpenAction
class LangResourceOpenController {

    @RequestMapping(
        "/lang/res",
        produces = arrayOf("text/plain"),
        method = arrayOf(RequestMethod.POST, RequestMethod.GET)
    )
    fun res(
        @Require lang: String,
        @Require productLineCode: String,
        @Require key: String
    ): String {

        //使用 ${} 做为嵌套 key
//        Regex("""\${'$'}\{[^}]""").findAll(key)

        mor.sys.langResource.query()
            .where { it.productLine.code mongoEquals productLineCode }
            .linkOr( { it.key mongoEquals key },{ it.cn mongoEquals key },{ it.en mongoEquals key })
            .toList()
            .apply {
                if (this.any() == false) {
                    var productLine = mor.dev.productLine.queryByCode(productLineCode).toEntity()
                        .must()
                        .elseThrow { "找不到产品线 ${productLineCode}" }

                    var ent = LangResource();
                    ent.productLine = IdCodeName(productLine.id, productLine.code, productLine.name)
                    ent.key = key;
                    ent.remark = "系统自动添加!"

                    mor.sys.langResource.doInsert(ent);

                    return key;
                }

                var item = this.firstOrNull { it.key == key } ?: this.first();

                if (lang == "cn") {
                    return item.cn.AsString(item.en).AsString(key)
                }

                if (lang == "en") {
                    return item.en.AsString(item.cn).AsString(key)
                }

                throw RuntimeException("不识别的语言编码:${lang}")
            }
    }

    @ApiOperation("详情")
    @PostMapping("/detail/{id}")
    fun detail(
        @Require id: String,
        request: HttpServletRequest
    ): ApiResult<LangResource> {
        mor.sys.langResource.queryById(id)
            .toEntity()
            .apply {
                if (this == null) {
                    return ApiResult.error("找不到数据")
                }

                return ApiResult.of(this)
            }
    }

    @ApiOperation("更新")
    @PostMapping("/save")
    fun save(
        @org.springframework.web.bind.annotation.RequestBody entity: LangResource,
        request: HttpServletRequest
    ): ApiResult<String> {
        //鉴权
        var userId = request.UserId;

        mor.sys.langResource.updateWithEntity(entity)
            .withColumns(request.requestParameterKeys)
            .run {
                if (entity.id.HasValue) {
                    return@run this.execUpdate()
                } else {
                    return@run this.execInsert()
                }
            }
            .apply {
                if (this == 0) {
                    return ApiResult.error("更新失败")
                }

                return ApiResult.of(entity.id)
            }
    }

    @ApiOperation("删除")
    @PostMapping("/delete/{id}")
    fun delete(
        @Require id: String,
        request: HttpServletRequest
    ): JsonResult {
        //鉴权
        var userId = request.UserId

        var entity = mor.sys.langResource.queryById(id).toEntity()
        if (entity == null) {
            return JsonResult.error("找不到数据")
        }

        mor.sys.langResource.deleteById(id)
            .exec()
            .apply {
                if (this == 0) {
                    return JsonResult.error("删除失败")
                }
                //实体上配置垃圾箱功能，可物理删除，会自动移到垃圾箱。
                return JsonResult()
            }
    }
}